import { defineStore } from 'pinia'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login.js'
import localCache from '@/utils/cache.js'
import router from '@/router/index.js'

import type { RouteRecordRaw } from 'vue-router'
import type { ILoginState } from './types.js'
import type { IAccount } from '@/service/login/types.js'

const useLoginStore = defineStore('ILoginStore', {
  state: (): ILoginState => ({
    token: '',
    userInfo: {}, // 用户信息
    userMenus: [] // 用户角色可见菜单
  }),
  getters: {
    test: (state) => {}
  },
  actions: {
    // 账号登录行为
    async accountLoginAction(account: IAccount) {
      // 1. 登录获取token
      const {
        code = '-1200',
        data: { id = 1124, token = 'sdfsdfkljsdklfjsdjkfh' }
      } = await accountLoginRequest(account)
      this.token = token
      localCache.setCache('token', token)

      // 2. 请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      localCache.setCache('userInfo', userInfo)

      // 3.请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role?.id)
      const userMenus = userMenusResult.data
      this.userMenus = userMenus
      mapMenusToRoutes()
      // 跳转到首页
      router.push('/main')
    },
    // 页面刷新后基于缓存重新初始化state数据，
    setupStoreState() {
      const token = localCache.getCache('token')
      if (token) this.token = token
      const routes = mapMenusToRoutes()
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  }
  // persist: true
})
// 根据用户权限动态加载routes
const mapMenusToRoutes = (userMenus: any[] = []): RouteRecordRaw[] => {
  const routes: RouteRecordRaw[] = []

  // 1.先去加载默认所有的routes
  const modules = import.meta.glob('@/views/**/*.ts', { eager: true })
  routes.push({
    path: '/main/system/user/role',
    component: () => import('@/views/main/system/user/role.vue')
  })
  routes.forEach((route) => {
    router.addRoute('main', route)
  })
  return routes
}
export { useLoginStore, mapMenusToRoutes }
